﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace GameModels
{
    public class PickingHelper
    {
        public static float RayIntersectsModel(Ray ray, Model model, Matrix modelTransform)
        {
            //Matrix inverseTransform = Matrix.Invert(modelTransform);
            //ray.Position = Vector3.Transform(ray.Position, inverseTransform);
            //ray.Direction = Vector3.TransformNormal(ray.Direction, inverseTransform);
            // Start off with a fast bounding sphere test.
            model.Root.Transform = modelTransform;
            Matrix[] transforms = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(transforms);
            float? currentD = null;
            foreach (ModelMesh mesh in model.Meshes)
            {
                BoundingSphere boundingSphere = mesh.BoundingSphere;
                boundingSphere = boundingSphere.Transform(transforms[mesh.ParentBone.Index]);
                float? d = boundingSphere.Intersects(ray);
                if (d >= 0 && (currentD == null || currentD > d))
                {
                    currentD = d;
                }
            }
            if (currentD != null)
            {
                return currentD.Value;
            }
            return -1;
        }

    }
}
